#include<iostream>
#include<pthread.h>
#include<unistd.h>
using namespace std;

pthread_mutex_t g_lock;
pthread_cond_t thread_a_cond;
pthread_cond_t thread_b_cond;

int g_is_my_turn = 0;

void* thread_a_start(void* args)
{
    (void)args;
    while(1)
    {
        pthread_mutex_lock(&g_lock);
        while(g_is_my_turn == 1)
        {
            pthread_cond_wait(&thread_a_cond, &g_lock);
        }
        cout << "hello thread A" << endl;
        sleep(1);
        g_is_my_turn++;
        pthread_mutex_unlock(&g_lock);
        pthread_cond_signal(&thread_b_cond);
    }
}

void* thread_b_start(void* args)
{
    (void)args;
    while(1)
    {
        sleep(1);
        pthread_mutex_lock(&g_lock);
        while(g_is_my_turn == 0)
        {
            pthread_cond_wait(&thread_b_cond, &g_lock);
        }
        cout << "hello thread B" << endl;
        sleep(1);
        g_is_my_turn--;
        pthread_mutex_unlock(&g_lock);
        pthread_cond_signal(&thread_a_cond);
    }
}

int main()
{
    pthread_mutex_init(&g_lock, nullptr);
    pthread_cond_init(&thread_a_cond, nullptr);
    pthread_cond_init(&thread_b_cond, nullptr);

    pthread_t thread_a, thread_b;
    int n = pthread_create(&thread_a, nullptr, thread_a_start, nullptr);
    if(n < 0)
    {
        perror("pthread_create error");
        return 0;
    }

    n = pthread_create(&thread_b, nullptr, thread_b_start, nullptr);
    if(n < 0)
    {
        perror("pthread_create error");
        return 0;
    }

    pthread_join(thread_a, nullptr);
    pthread_join(thread_b, nullptr);
    pthread_mutex_destroy(&g_lock);
    pthread_cond_destroy(&thread_a_cond);
    pthread_cond_destroy(&thread_b_cond);
    
    return 0;
}